/*
 * Copyright 2024 Haulmont.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.jmix.securityflowui.security;

import com.google.common.base.Strings;
import com.vaadin.flow.component.page.ExtendedClientDetails;
import io.jmix.core.security.DeviceTimeZoneProvider;
import io.jmix.flowui.sys.ExtendedClientDetailsProvider;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.TimeZone;

@Component("sec_DeviceTimeZoneProviderImpl")
public class DeviceTimeZoneProviderImpl implements DeviceTimeZoneProvider {

    protected ExtendedClientDetailsProvider clientDetailsProvider;

    public DeviceTimeZoneProviderImpl(ExtendedClientDetailsProvider clientDetailsProvider) {
        this.clientDetailsProvider = clientDetailsProvider;
    }

    @Override
    public TimeZone getDeviceTimeZone() {
        ExtendedClientDetails clientDetails = clientDetailsProvider.getExtendedClientDetails();
        return clientDetails != null ? detectTimeZone(clientDetails) : null;
    }

    protected TimeZone detectTimeZone(ExtendedClientDetails details) {
        String timeZoneId = details.getTimeZoneId();

        if (!Strings.isNullOrEmpty(timeZoneId)) {
            return TimeZone.getTimeZone(timeZoneId);
        } else {
            int offset = details.getTimezoneOffset() / 1000 / 60;
            char sign = offset >= 0 ? '+' : '-';
            int absOffset = Math.abs(offset);

            String hours = StringUtils.leftPad(String.valueOf(absOffset / 60), 2, '0');
            String minutes = StringUtils.leftPad(String.valueOf(absOffset % 60), 2, '0');

            return TimeZone.getTimeZone("GMT" + sign + hours + minutes);
        }
    }
}
